<template>
    <a-spin :spinning="loading">
        <div class="app-page-list-tools">
            <slot name="tools"></slot>
        </div>
        <div>
            <slot name="table"></slot>
        </div>
        <div class="app-page-list-data_pagination" v-if="pagination">
            <a-pagination
                show-quick-jumper
                :total="total"
                :page-size-options="pageSizeOptions"
                :page-size="_pageSize"
                @change="onChange"
                show-size-changer
                @showSizeChange="onShowSizeChange"
            >
                <template #buildOptionText="props">
                    <span>{{ props.value }}条/页</span>
                </template>
            </a-pagination>
        </div>
    </a-spin>
</template>

<script setup lang="ts">
import { HttpClient } from '@/core/HttpClient';
import { ref, watch, defineProps, withDefaults, defineEmits, defineExpose } from 'vue'

/**
 * 参数
*/
interface IProps {
    /**
     * 请求地址
    */
    url: string;
    /**
     * 查询参数
    */
    data: {};
    
    /**页码大小*/
    pageSize?: number;

    /**加载*/
    loading?: boolean;

    /**是否显示分页*/
    pagination?: boolean
}

const props = withDefaults(
    defineProps<IProps>(),
    {
        loading: true,
        pagination: true,
        //pageSize: 5
    }
);


const emits = defineEmits(["onRequestBefore", "onGetData"]); 
const pageSizeOptions = ref(['10', '20', '30', '40', '50']);
const total = ref(0);
let _pageSize = props.pageSize ?? 10;

if (props.pageSize != undefined) {
    if (pageSizeOptions.value.indexOf(props.pageSize + '') < 0) {
        pageSizeOptions.value.unshift(props.pageSize + '');
    }
}
//分页选中进度
const onChange = (page: any, pageSize: any) => {
    onLoadData(page, pageSize, props.data);
    _pageSize = pageSize;
};

//分页下拉列表变动
const onShowSizeChange = (current: number, size: number) => {
    onLoadData(current, size, props.data);
    _pageSize = size;
}

//外部触发搜索方法
const onSearch = () => {
    onLoadData(1, _pageSize, props.data);
}


//加载数据
const onLoadData = (page = 1, pageSize = 10, queryParameters = {}) => {
    let queryRequest = Object.assign({
        pageIndex: page,
        pageSize: pageSize
    }, queryParameters);
    emits("onRequestBefore");
    HttpClient.post<any>(props.url ?? "", queryRequest).then((res) => {
        total.value = res.data.total;
        emits("onGetData", res.data.data);
    });
}

onLoadData(1, props.pageSize ?? 10, props.data);

//监听
watch([props.loading], (newVla, perVal) => {
    //console.log("perVal", perVal);
    //console.log("newVla", newVla);
})


defineExpose({
    onSearch
})

</script>